package com.woniu34.cinema.dashboard.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu34.cinema.dashboard.entity.Dashboard;
import com.woniu34.cinema.dashboard.mapper.DashboardMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/dashboard")
@CrossOrigin
@Slf4j
public class DashboardController {

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    private static CopyOnWriteArrayList<Session> sessionList=new CopyOnWriteArrayList<>();


    @Autowired
    private DashboardMapper dashboardMapper;

    /**
     * 连接建立成功调用的方法
     */

    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        sessionList.add(session);//把session保存在列表中
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */

    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     * 客户端发送过来的消息
     */

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        this.sendMessage("Hello, " + message, session);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }


    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }

    @Scheduled(fixedRate = 5000 )//每5秒钟运行一次
    public void sendMessageToAllClients(){
        System.out.println("推送消息给客户端");
        if(sessionList.size()>0){
            List<Dashboard> dashboardList = dashboardMapper.queryAll();
            ObjectMapper mapper = new ObjectMapper();
            for (Session session : sessionList) {
                try {
                    if(session.isOpen()){
                        session.getBasicRemote().sendText(mapper.writeValueAsString(dashboardList));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
